package com.ccit.greenlife.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private  static final String KEY = "czjy";

        //生成
        public static String genToken(Map<String, Object> claims){
            //生成jwt的代码
            return  JWT.create()
                    .withClaim("claims", claims)//添加载荷
                    .withExpiresAt(new Date(System.currentTimeMillis() + 1000*60*60*12))//过期时间(12h)
                    .sign(Algorithm.HMAC256(KEY));//指定算法，配置密钥
        }

        //验证
        public static Map<String, Object> ParseToken(String token){
            return  JWT.require(Algorithm.HMAC256(KEY)).build()
                    .verify(token)//验证token，生成解析后的jwt对象
                    .getClaim("claims")//获取指定载荷（如果存在）
                    .asMap();
                    //{"id":1,"username":"张三"}
        }

        public static void main(String[] args) {
            System.out.println(ParseToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsiaWQiOiI5MGUwNDZkNWE0OWI0ZGI1YjEyMTNlYTk3YjkzMzdmNSIsInVzZXJuYW1lIjoiZ2pzIn0sImV4cCI6MTcyNjU4MDk4M30.PpDaY_6Jnpr_ww-srU6B4ACpwoUqkscVML_ib3VeMHc"));
        }//{id=1, username=cain11}

}
